<template>
  <div class="task-detail-container" v-loading="loading">
    <!-- 顶部操作区 -->
    <div class="task-detail-header common-detail-header">
      <el-button v-if="editedPermission" type="plain-third" @click="handleEdit">
        <i class="iconfont icon-edit-square"></i>{{$t('common.base.edit')}}
      </el-button>
      <el-button
        v-if="deletePermission"
        type="plain-third"
        @click="handleDelete"
      >
        <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
      </el-button>
      <el-button type="plain-third" @click="handlePreview">
        <i class="iconfont icon-qrcode"></i>{{$t('common.base.preview')}}
      </el-button>
      <template v-if="putawayPermission">
        <el-button type="plain-third" v-if="isShowBtn" @click="handleAdded">
          <i class="iconfont icon-long-arrow-up"></i>{{$t('goods.detail.onShelves')}}
        </el-button>
        <el-button type="plain-third" v-else @click="handleSoldOut">
          <i class="iconfont icon-long-arrow-down"></i>{{$t('goods.detail.lowerShelf')}}
        </el-button>
      </template>
    </div>

    <div v-if="taskLayout === 1" class="detail_h">
      <div class="detail">
        <!-- start 详情平铺布局 -->
        <BaseTileLayoutTabBar
          v-if="taskLayout === 1"
          :bar-list="taskLayoutTabBarList"
          :now-item="leftActiveTab"
          @changeItem="tabBarChangeItem"
          @openLayoutModal="openBaseLayoutModal"
        ></BaseTileLayoutTabBar>
        <!-- end 详情平铺布局 -->
      </div>
    </div>

    <!-- 商品详情折叠面板 -->
    <base-collapse
      class="task-detail-main-content detail-main-content"
      :direction.sync="collapseDirection"
      :hide-part-collapse="hidePartCollapse"
      style="position: relative"
    >
      <!-- 商品详情 -->
      <template slot="left">
        <div
          class="task-detail-main-content-left detail-main-content-left"
          v-show="collapseDirection != 'left'"
        >
          <div class="detail">
            <div class="detail-layout">
              <BaseTileLayoutTabBar
                v-if="taskLayout === 2"
                :bar-list="leftBarList"
                :now-item="leftActiveTab"
                :structure="2"
                @openLayoutModal="openBaseLayoutModal"
              ></BaseTileLayoutTabBar>
              <GoodsDetail 
                v-if="leftActiveTab === 'detail'" 
                :fields="_goodsFields" 
                :value="goodsInfo" 
                :form-cell-count="formCellCount"
              />
            </div>
          </div>
        </div>
        <div class="collapse-left" v-show="collapseDirection == 'left'">
          {{$t('goods.detail.productInfo')}}
        </div>
      </template>

      <!-- 动态信息 -->
      <template slot="right">
        <div
          class="task-detail-main-content-right detail-main-content-right"
          v-show="collapseDirection != 'right'"
        >
          <BaseBarV3
            v-if="taskLayout == 2"
            :bar-list="tabBarList"
            :now-item="rightActiveTab"
            @changeItem="tabBarChangeItem"
          ></BaseBarV3>
          <GoodsInfoRecord
            v-if="rightActiveTab == 'record'"
            ref="goodsInfoRecordRef"
            :collapse-direction="collapseDirection"
            :goods-id="goodsId"
            @changeRecordCount="handleChangeRecordCount"
          />
        </div>
      </template>
      <template slot="rightExtend">
        <button class="right-extend-btn" @click="rightTabs = 'record'">
          <i class="iconfont icon-message1"></i>{{$t('common.base.addRemark')}}
        </button>
      </template>
    </base-collapse>

    <!-- 商品上架提示弹窗 -->
    <GoodsAddedDialog ref="goodsAddedRef" @reloadPage="reloadPage" />
    <!-- 通栏弹窗 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="baseLayout"
      :columns="formCellCount"
      @changeLayout="changeDetailLayout">
    </biz-layout-modal>
  </div>
</template>

<script>
import _ from 'lodash';
import qs from '@src/util/querystring';
import { goodsFields } from '@src/modules/linkc/field.js';
import GoodsDetail from 'src/modules/linkc/goods/components/GoodsDetail.vue';
import GoodsInfoRecord from 'src/modules/linkc/goods/components/GoodsInfoRecord.vue';
import GoodsAddedDialog from '@src/modules/linkc/goods/components/GoodsAddedDialog.vue';
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue';
import {
  queryGoodsDetail,
  deleteGoods,
  updatePutawayStatus,
  checkPrice,
} from '@src/api/PortalApi.ts';
import AuthMixin from '@src/mixins/authMixin';
import AuthUtil from '@src/util/auth';
import AuthEnum from '@model/enum/AuthEnum.ts';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { useStateSystemViewLayout } from 'pub-bbx-utils'
import { t as $t } from '@src/locales'

export default {
  mixins: [AuthMixin],
  components: {
    GoodsDetail,
    GoodsInfoRecord,
    GoodsAddedDialog,
    BaseTileLayoutTabBar,
    BaseBarV3,
  },
  data() {
    return {
      loading: false,
      taskLayoutTabBarList: [], 
      tabBarList: [
        {
          tabName: 'record',
          disabled: true,
          tabShow: true,
          tabLabel: $t('common.base.dynamicInfo'),
          position: 'right'
        }
      ],
      collapseDirection: '',
      leftTabs: 'detail',
      leftActiveTab: 'detail',
      rightTabs: 'record',
      rightActiveTab: 'record',
      fields: [], // 商品字段
      goodsInfo: {
        id: '',
      }, // 商品信息
      recordCount: 0, // 动态信息数量
      qrcode: null,
      goodsFields: [],
      baseLayout: 2,
      formCellCount: 1,
      tabPosition: '',
      currentTab: {
        tabName: ''
      },
    };
  },
  computed: {
    // 删除权限
    deletePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.DELETE_GOODS);
    },
    // 编辑权限
    editedPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.EDIT_GOODS);
    },
    // 上下架权限
    putawayPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.PUTAWAY_GOODS);
    },
    goodsId() {
      const queryObject = qs.parse(window.location.search);

      return queryObject.id ?? '';
    },
    _goodsFields() {
      this.goodsFields = _.cloneDeep(goodsFields);
      const filterArr = [
        'base_info',
        'originType',
        'hasInventory',
        'originPrice',
        'viewNumber',
      ];

      if (this.goodsInfo?.originType === 2) {
        filterArr.push('expressCost', 'serviceCost');
      }

      if (this.goodsInfo?.serviceType === 2) {
        filterArr.push('expressCost');
      }

      if (this.goodsInfo?.serviceType === 1) {
        filterArr.push('serviceCost', 'isAppointmentSupported');
      }

      return goodsFields.filter(field => !filterArr.includes(field.fieldName));
    },
    isShowBtn() {
      return this.goodsInfo?.putawayStatus === 0;
    },
    taskLayout() {
      return this.baseLayout
    },
    leftBarList() {
      return [{
        tabName: 'detail',
        disabled: true,
        tabShow: true,
        tabLabel: $t('goods.detail.productInfo'),
        position: 'left'
      }]
    },
    rightBarList() {
      return [...this.tabBarList]
    },
    hidePartCollapse() {
      if(this.taskLayout === 1) return this.tabPosition === 'left' ? 'right' : 'left';
      return '';
    },
  },
  created() {
    this.collapseDirection =
      sessionStorage.getItem(`goods_collapseDirection_${this.goodsId}`) || '';

    this.handleGetGoodsInfo();
  },
  methods: {
    tabBarChangeItem(item) {
      this.tabPosition = item.position;
      if(this.taskLayout === 1 || item.position === 'left') {
        this.leftActiveTab = item.tabName;
      } 
      if(item.position === 'right') {
        this.rightActiveTab = item.tabName;
      } 
    },
    initRightTabBar() {
      if (this.taskLayout === 1) {
        this.tabPosition = 'left';
      }
      this.taskLayoutTabBarList = this.rightBarList;
      if(this.taskLayoutTabBarList.findIndex(item => item.tabName === 'detail') === -1) {
        this.taskLayoutTabBarList.unshift(...this.leftBarList);
      }
    },
    baseUpdate(item) {
      this.currentTab = item;
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeDetailLayout(type, columns) {
      this.leftActiveTab = 'detail' 
      this.baseLayout = type
      this.tabPosition = 'left'
      if(type === 2) {
        this.rightActiveTab = 'record' 
      }
      this.formCellCount = columns * 1
    },
    async initFormBuilderCellCount(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.baseLayout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    },
    reloadPage() {
      this.handleGetGoodsInfo();
      this.$refs.goodsInfoRecordRef.initRecord();
    },
    handleEdit() {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsEdit,
        key: this.goodsId,
        params: `id=${this.goodsId}`,
        fromId,
      });
    },
    handleDelete() {
      this.$confirm(this.$t('goods.tips.confirmTip'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(async () => {
        const { code, message } = await deleteGoods({ ids: [this.goodsId] });

        if (code !== '200') {
          return this.$message.error(message || this.$t('common.base.deleteFail'));
        }
        this.$message.success(this.$t('common.base.deleteSuccess'));

        let id = window.frameElement.dataset.id;
        this.$platform.closeTab(id);
      });
    },
    // 预览商品
    handlePreview() {
      if (!this.goodsId) return;

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsPreview,
        key: this.goodsId,
        params: `id=${this.goodsId}&name=${this.goodsInfo.commodityName}&from=detail`,
      });
    },
    // 商品上架
    async handleAdded() {
      try {
        if (!this.goodsInfo?.id) return;

        const ids = [this.goodsInfo.id];
        const res = await checkPrice({ ids });
        if (res.code !== '200') {
          return this.$message.error(this.$t('goods.tips.verifyPriceFailed'));
        }
        if (res?.data?.length) {
          return this.$refs.goodsAddedRef.open(res.data, ids);
        }

        const { code } = await updatePutawayStatus({ ids, putawayStatus: 1 });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.launchFailed'));
        }

        this.$message.success(this.$t('goods.tips.launchSuccess'));
        setTimeout(() => {
          this.reloadPage();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    // 下架商品
    async handleSoldOut() {
      try {
        if (!this.goodsInfo?.id) return;

        const ids = [this.goodsInfo.id];
        const { code } = await updatePutawayStatus({ ids, putawayStatus: 0 });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.lowerShelfFailed'));
        }

        this.$message.success(this.$t('goods.tips.lowerShelfSuccess'));
        setTimeout(() => {
          this.reloadPage();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    async handleGetGoodsInfo() {
      try {
        this.loading = true;

        const { code, data } = await queryGoodsDetail({ id: this.goodsId });

        if (code !== '200' || !data) {
          this.loading = false;
          return this.$message.error(this.$t('goods.tips.obtainInfoFailed'));
        }

        this.loading = false;
        this.goodsInfo = data;
        this.goodsInfo.catalogIds =
          this.goodsInfo?.productTypeList?.map(v => v.id) || [];
        let { hasSpecs=0, specifications=[], specsList=[]} = this.goodsInfo
        if(hasSpecs) {
          this.goodsInfo.specsList = specsList.map(items => {
            let obj = {}
            items.specsInfo.forEach(v => {
              obj[v.specsGroupName] = v.specsInfoValue
            })
            return {
              ...items,
              ...obj
            }
          })
          this.goodsInfo.specifications = (specifications || [])
          .map(item => {
            return { name: item.name, fieldName: item.fieldName };
          })
          .concat([
            { name: this.$t('common.base.serialNumber'), fieldName: 'serialNumber', minWidth: 150 },
            { name: this.$t('common.base.price'), fieldName: 'salePrice' },
            { name: this.$t('common.form.preview.sparepart.label4'),  fieldName: 'inventory' },
          ]) || []
        }
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    handleChangeRecordCount(num) {
      this.recordCount = num;
    },
  },
  watch: {
    collapseDirection(newValue) {
      sessionStorage.setItem(
        `goods_collapseDirection_${this.goodsId}`,
        newValue
      );
    },
  },
  async mounted() {
    this.currentTab = {
      tabName: this.leftActiveTab
    }
    await this.initFormBuilderCellCount()

    this.initRightTabBar()
  },
};
</script>

<style lang="scss">
@import '@src/modules/task/view/TaskDetailView.scss';
@import '@src/assets/scss/common-detail.scss';
</style>

<style lang="scss" scoped>
.task-detail-header {
  min-height: 56px;
  padding: 12px 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
  display: flex;

  .el-button {
    margin-left: 12px;
  }
}

.detail-main-content {
  height: 100%;
}

.detail-main-content-left ::v-deep .el-tabs__nav,
.detail-main-content-right ::v-deep .el-tabs__nav {
  white-space: normal;
  // background: #fff;
  padding-right: 44px;
  height: auto;
  font-size: 0;
  .el-tabs__item {
    padding: 0 !important;
    margin: 0 24px;
    height: 40px;
    line-height: 40px;
    max-width: 290px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    vertical-align: middle;
    &.is-active {
      border-bottom: 2px solid $color-primary-light-6;
    }
  }
  .el-tabs__active-bar {
    display: none;
  }
}

// .detail-main-content-right ::v-deep .el-tab-pane {
//   padding: 16px;
// }

.task-detail-main-content .el-tabs__content .el-tab-pane {
  overflow: auto !important;
}
.detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  .detail-layout {
    flex: 1;
    background-color: #fff;
    height: 100%;
    overflow: auto;
    padding-bottom: 40px;
  }
}
.layoutDialog {
  position: absolute;
  right: 0;
  width: fit-content;
  height: 39px;
  align-items: normal;
  background: #fafafa;
  &::after {
    border: none;
  }
}
.layoutDialog2 {
  position: absolute;
}
.detail_h {
  height: 100%;
}
</style>
